<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useForm } from '@/hooks/arco/useForm';
  import { useUploader } from '@/hooks/useUploader';
  import {
    createTotalArchive,
    updateTotalArchive,
    queryTotalArchiveInfo,
    genResourceUploadToken,
  } from '@/api/reemployment-management/document';
  import * as Lodash from 'lodash';
  import { fillData, getInfoFromImageResource } from '@/views/lhj-v1/util';
  import PhotoItem from './photo-item.vue';

  const emits = defineEmits(['cancel', 'update']);
  const props = defineProps({
    id: {
      type: String,
      default: '',
    },
  });

  const baseNameMap = {
    id: { key: 'id', label: '', placeholder: '' },
    title: { key: 'title', label: '培训题目', placeholder: '请输入培训题目' },
    datetime: {
      key: 'datetime',
      label: '培训时间',
      placeholder: '请选择培训时间',
    },
    datetimeRange: {
      key: 'datetimeRange',
      label: '培训时间',
      placeholder: '请选择培训时间',
    },
    startDate: { key: 'startDate' },
    endDate: { key: 'endDate' },
    place: { key: 'address', label: '培训地点', placeholder: '请输入培训地点' },
    teacher: {
      key: 'teachers',
      label: '培训教师',
      placeholder: '请输入培训教书，多人用"；"隔开',
    },
    project: {
      key: 'project',
      label: '培训项目',
      placeholder: '请输入培训项目',
    },
    teacherQualificationPhotoResIds: { key: 'teacherQualificationPhotoResIds' },
    courseTableResIds: { key: 'courseTableResIds' },
    studentRosterResIds: { key: 'studentRosterResIds' },
    signInTableResIds: { key: 'signInTableResIds' },
    assessmentTableResIds: { key: 'assessmentTableResIds' },
    trainFolioResIds: { key: 'trainFolioResIds' },
  };

  const loading = ref(false);
  const infoBase = useForm({
    state: {
      [baseNameMap.id.key]: '',
      [baseNameMap.title.key]: '',
      [baseNameMap.datetimeRange.key]: [],
      [baseNameMap.place.key]: '',
      [baseNameMap.teacher.key]: '',
      [baseNameMap.project.key]: '',
    },
    rules: {
      [baseNameMap.title.key]: {
        required: true,
        message: baseNameMap.title.placeholder,
      },
      [baseNameMap.datetimeRange.key]: {
        required: true,
        message: baseNameMap.datetimeRange.placeholder,
      },
      [baseNameMap.place.key]: {
        required: true,
        message: baseNameMap.place.placeholder,
      },
      [baseNameMap.teacher.key]: {
        required: true,
        message: baseNameMap.teacher.placeholder,
      },
      [baseNameMap.project.key]: {
        required: true,
        message: baseNameMap.project.placeholder,
      },
    },
  });
  const uploader1 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
    onOk: (result) => {
      console.log('uploader1:', result);
    },
  });
  const uploader2 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
  });
  const uploader3 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
  });
  const uploader4 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
  });
  const uploader5 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
  });
  const uploader6 = useUploader({
    apiFun: genResourceUploadToken,
    props: {
      listType: 'picture-card'
    },
  });

  const handleSave = async () => {
    await infoBase.validate();
    loading.value = true;
    // 数据处理
    const data: any = Lodash.cloneDeep(infoBase.state);
    if (
      data[baseNameMap.datetimeRange.key] &&
      data[baseNameMap.datetimeRange.key].length > 0
    ) {
      [data[baseNameMap.startDate.key], data[baseNameMap.endDate.key]] =
        data[baseNameMap.datetimeRange.key];
    }
    data[baseNameMap.teacherQualificationPhotoResIds.key] = uploader1.getResourceIds();
    data[baseNameMap.courseTableResIds.key] = uploader2.getResourceIds();
    data[baseNameMap.studentRosterResIds.key] = uploader3.getResourceIds();
    data[baseNameMap.signInTableResIds.key] = uploader4.getResourceIds();
    data[baseNameMap.assessmentTableResIds.key] = uploader5.getResourceIds();
    data[baseNameMap.trainFolioResIds.key] = uploader6.getResourceIds();
    let apiFunc = createTotalArchive;
    let msg = '创建成功！';
    if (props.id) {
      apiFunc = updateTotalArchive;
      msg = '保存成功！';
    }
    apiFunc(data)
      .then((res) => {
        Message.success(msg);
        emits('update');
      })
      .catch((err) => {})
      .finally(() => {
        loading.value = false;
      });
  };

  watch(
    () => props.id,
    (newVal) => {
      if (newVal) {
        loading.value = true;
        queryTotalArchiveInfo(newVal)
          .then((res) => {
            res[baseNameMap.datetimeRange.key] = [
              res[baseNameMap.startDate.key],
              res[baseNameMap.endDate.key],
            ];
            infoBase.state = fillData(infoBase.state, res);
            const maps = [
              {uploader: uploader1, key: baseNameMap.teacherQualificationPhotoResIds.key},
              {uploader: uploader2, key: baseNameMap.courseTableResIds.key},
              {uploader: uploader3, key: baseNameMap.studentRosterResIds.key},
              {uploader: uploader4, key: baseNameMap.signInTableResIds.key},
              {uploader: uploader5, key: baseNameMap.assessmentTableResIds.key},
              {uploader: uploader6, key: baseNameMap.trainFolioResIds.key},
            ];
            maps.forEach((item)=>{
              const imgItems = Lodash.cloneDeep(res[item.key])
              if (imgItems) {
                item.uploader.props.defaultFileList = [];
                for (let i=0 ; i<imgItems.length; i+=1) {
                  item.uploader.props.defaultFileList?.push(getInfoFromImageResource(imgItems[i]))
                }
              }
            });
          })
          .catch((err) => {})
          .finally(() => {
            loading.value = false;
          });
      }
    },
    { immediate: true }
  );
</script>

<template>
  <div class="md-total-add">
    <div class="md-ta-item md-ta-form">
      <div><span style="font-weight: 600; font-size: 15px">基本信息</span></div>
      <a-form
        style="margin-top: 10px"
        v-bind="infoBase.bindProps"
        layout="vertical"
        :wrapper-col-props="{ span: 3 }"
      >
        <!-- 1 -->
        <a-row justify="space-between">
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.title.key"
              :label="baseNameMap.title.label"
              required
            >
              <a-input
                v-model="infoBase.state[baseNameMap.title.key]"
                :placeholder="baseNameMap.title.placeholder"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.datetimeRange.key"
              :label="baseNameMap.datetimeRange.label"
              required
            >
              <a-range-picker
                v-model="infoBase.state[baseNameMap.datetimeRange.key]"
                format="YYYY-MM-DD"
                style="width: 100%"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.place.key"
              :label="baseNameMap.place.label"
              required
            >
              <a-input
                v-model="infoBase.state[baseNameMap.place.key]"
                :placeholder="baseNameMap.place.placeholder"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 2 -->
        <a-row justify="space-between">
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.teacher.key"
              :label="baseNameMap.teacher.label"
              required
            >
              <a-input
                v-model="infoBase.state[baseNameMap.teacher.key]"
                :placeholder="baseNameMap.teacher.placeholder"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item
              :field="baseNameMap.project.key"
              :label="baseNameMap.project.label"
              required
            >
              <a-input
                v-model="infoBase.state[baseNameMap.project.key]"
                :placeholder="baseNameMap.project.placeholder"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="7"></a-col>
        </a-row>
      </a-form>
    </div>
    <div class="md-ta-imgs" v-if="!loading">
      <PhotoItem title="培训教师资质照片" :uploader="uploader1" />
      <PhotoItem title="培训课程表" :uploader="uploader2" />
      <PhotoItem title="培训学员花名册" :uploader="uploader3" />
      <PhotoItem title="培训签到表" :uploader="uploader4" />
      <PhotoItem title="培训考核表" :uploader="uploader5" />
      <PhotoItem title="培训风采" :uploader="uploader6" />
    </div>
    <div class="m-bottom-btns" style="padding-right: 30px">
      <a-space>
        <ae-button purpose="cancel" @click="emits('cancel')">取消</ae-button>
        <ae-button purpose="save" @click="handleSave">保存</ae-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .md-total-add {
    color: var(--color-text-1);
    padding: 10px;
    padding-bottom: 40px;
    height: calc(100% - 30px);
    overflow-x: hidden;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .md-ta-item {
    padding: 10px 20px 2px;
    border-radius: 4px;
    background-color: var(--color-fill-1);
    margin-bottom: 20px;
  }

  .md-ta-imgs {
    display: flex;
    flex-direction: column;
    row-gap: 10px;
  }
</style>
